const { defineConfig } = require("@vue/cli-service");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const CompressionPlugin = require("compression-webpack-plugin");
const path = require("path");

// 生产环境压缩文件类型
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i;

module.exports = defineConfig({
  // 基本路径
  publicPath: process.env.NODE_ENV === "production" ? "/vue-prod/" : "/",
  // 输出文件目录
  outputDir: process.env.NODE_ENV === "production" ? "dist/vue-prod" : "dist",
  // 静态资源目录
  assetsDir: "static",
  // 是否开启eslint保存检测
  lintOnSave: process.env.NODE_ENV === "development",
  // 是否开启生产环境的 source map
  productionSourceMap: false,
  // 是否开启并行打包
  parallel: require("os").cpus().length > 1,

  // CSS 配置
  css: {
    // 是否使用css分离插件 ExtractTextPlugin
    extract: process.env.NODE_ENV === "production",
    // 开启 CSS source maps?
    sourceMap: process.env.NODE_ENV === "development",
    // css预设器配置项
    loaderOptions: {
      scss: {
        additionalData: `@import "@/assets/style/variables.scss";`,
      },
    },
  },

  // webpack配置
  chainWebpack: (config) => {
    // 打包分析
    if (process.env.ANALYZE) {
      config.plugin("webpack-bundle-analyzer").use(BundleAnalyzerPlugin);
    }

    // 生产环境配置
    if (process.env.NODE_ENV === "production") {
      // 压缩CSS
      config.plugin("css-minimizer-webpack-plugin").use(CssMinimizerPlugin);

      // Gzip压缩
      config.plugin("compression-webpack-plugin").use(CompressionPlugin, [
        {
          filename: "[path][base].gz",
          algorithm: "gzip",
          test: productionGzipExtensions,
          threshold: 10240,
          minRatio: 0.8,
        },
      ]);

      // 图片压缩
      config.module
        .rule("images")
        .use("image-webpack-loader")
        .loader("image-webpack-loader")
        .options({
          mozjpeg: { progressive: true, quality: 65 },
          optipng: { enabled: false },
          pngquant: { quality: [0.65, 0.9], speed: 4 },
          gifsicle: { interlaced: false },
          webp: { quality: 75 },
        });
    }

    // 代码分割
    config.optimization.splitChunks({
      chunks: "all",
      cacheGroups: {
        libs: {
          name: "chunk-libs",
          test: /[\\/]node_modules[\\/]/,
          priority: 10,
          chunks: "initial",
        },
        elementUI: {
          name: "chunk-elementUI",
          priority: 20,
          test: /[\\/]node_modules[\\/]_?element-ui(.*)/,
        },
        commons: {
          name: "chunk-commons",
          minChunks: 2,
          priority: 5,
          reuseExistingChunk: true,
        },
      },
    });

    // 别名配置
    config.resolve.alias
      .set("@", path.resolve(__dirname, "src"))
      .set("assets", path.resolve(__dirname, "src/assets"))
      .set("components", path.resolve(__dirname, "src/components"));
  },

  // 开发服务器配置
  devServer: {
    host: "0.0.0.0",
    port: 8080,
    open: true,
    hot: true,
    compress: true,
    client: {
      overlay: {
        warnings: false,
        errors: true,
      },
    },
    proxy: {
      "/api": {
        target: "http://localhost:8080",
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          "^/api": "",
        },
        logLevel: "debug",
      },
    },
  },

  // 插件配置
  pluginOptions: {
    // 自动导入组件
    "style-resources-loader": {
      preProcessor: "scss",
      patterns: [path.resolve(__dirname, "src/assets/style/variables.scss")],
    },
  },
});
